import time

from util.DataUtil import *
import re

# 向set集合里加入元素set_obj set集合, iteration可迭代的容器
from util.DataUtil import DataUtil

DATA_FiLE_PATH = "./file/" # 定义当前的目录，方便在linux下切换

def timer(func):
    def call_func(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        total_time = end_time - start_time
        print(f"{func.__name__}用时{int(total_time // 60)}分{total_time % 60:.3f}秒")
        return result

    return call_func


def set_add_element(set_obj, iteration):
    for item in iteration:
        item = str(item)
        if item != "nan":  # 为nan不加
            set_obj.add(item)


def set_add_element2(set_obj, iteration):
    for item in iteration:
        item = str(item)
        pattern = "[零一二三四五六七八九0-9]+"
        if item != "nan" and len(re.findall(pattern, item)) != 0:  # 为nan不加
            set_obj.add(item)


# 模型训练类，模型训练交给这个类做
class AddressMatchingModelTrain:
    def __init__(self,fileName):
        """

        :param fileName: 训练文件
        """
        self.dataUtil = DataUtil(fileName)  # 读取当前模型

    def train(self, addressMatchingModel):
        # 为模型添加字典总结出来的基础数据
        self.add_basic_data(addressMatchingModel)

        # ['地址名称', '行政区划中文', '街路巷中文', '门牌号', '门牌后缀中文', '幢楼号', '幢楼后缀中文', '地址类型'
        # 用标准地址结构化数据训练模型
        set_add_element2(addressMatchingModel.JLS, self.dataUtil.get_column("街路巷中文").values)
        set_add_element(addressMatchingModel.buildingNumberSuffix, self.dataUtil.get_column("幢楼后缀中文").values)
        set_add_element(addressMatchingModel.houseNumberSuffix, self.dataUtil.get_column("门牌后缀中文").values)

        for item in addressMatchingModel.JLS.copy():
            if not (self.is_suffix(item, addressMatchingModel.houseNumberSuffix)
                    or self.is_suffix(item,addressMatchingModel.buildingNumberSuffix)
                    or self.is_suffix( item, addressMatchingModel.roomNumberSuffix)):
                # 假如后缀数数据不存在就去掉该数据
                addressMatchingModel.JLS.remove(item)

    def is_suffix(self, jlx, list_suffix):
        for item in list_suffix:
            if item in jlx:
                return True
        return False

    # 添加模型的基础数据
    def add_basic_data(self, addressMatchingModel):
        # 街路巷数据
        set_add_element2(addressMatchingModel.JLS, self.dataUtil.basic_data["JLX"])

        # 后缀数据
        set_add_element(addressMatchingModel.buildingNumberSuffix, self.dataUtil.basic_data["buildingNumberSuffix"])
        set_add_element(addressMatchingModel.houseNumberSuffix, self.dataUtil.basic_data["houseNumberSuffix"])
        set_add_element(addressMatchingModel.roomNumberSuffix, self.dataUtil.basic_data["roomNumberSuffix"])
